﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
#if WINDOWS_PHONE
using System.Windows;

#else
using Windows.UI.Xaml;

#endif

namespace MetroEventToCommand
{
    public class EventToCommandCollection : ObservableCollection<EventToCommand>
    {
        internal FrameworkElement Element { get; set; }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            // set parent element in each added eventtocommand
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                //TODO: warn user?
                if (Element == null)
                    return;

                foreach (EventToCommand newItem in e.NewItems)
                {
                    newItem.Element = Element;
                }
            }

            // remove parent element in each removed eventtocommand.
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (EventToCommand newItem in e.NewItems)
                {
                    newItem.Element = null;
                }
            }

            base.OnCollectionChanged(e);
        }
    }


    public class EventToCommandManager
    {
        internal static readonly DependencyProperty CollectionProperty =
            DependencyProperty.RegisterAttached(
                "CollectionPropertyInternal", // Shadow the name so the parser does not skip GetEventToCommandCollection
                typeof(EventToCommandCollection),
                typeof(EventToCommandManager), null);



        internal static EventToCommandCollection GetCollectionPropertyInternal(FrameworkElement item)
        {
            var collection = (EventToCommandCollection)item.GetValue(CollectionProperty);
            if (collection == null)
            {
                collection = new EventToCommandCollection();
                collection.Element = item;
                item.SetValue(CollectionProperty, collection);
            }
            return collection;
        }

        internal static void SetCollectionPropertyInternal(FrameworkElement item, EventToCommandCollection value)
        {
            item.SetValue(CollectionProperty, value);
        }

        public static EventToCommandCollection GetCollection(FrameworkElement item)
        {
            return GetCollectionPropertyInternal(item);
        }

        public static void SetCollection(FrameworkElement item, EventToCommandCollection value)
        {
            SetCollectionPropertyInternal(item, value);
        }
    }
}
